//Time-stamp: <Modified by LuBin on 2011.05.05 17:34:04>
/* 文件copy 速度测试 */
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
//#include<sys/types.h>
//#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<sys/time.h>


#define SIZE_1M   (1024*1024)
#define BUFFERCAP (64*SIZE_1M)
static 	char buffer[BUFFERCAP]; 

//#define BUFFERCAP (64)


int copyfile(char *filename1,char* filename2){

    int source,target;
	int bytes_read,bytes_write;
	float bytes_sum = 0;

	char *ptr;

	struct timeval start;
	struct timeval end;
	float time_use = 0;

	
	
	/* open souce */
	if( ( source = open( filename1, O_RDONLY ) ) == -1 )
		{
			printf("Open %s Error\n", filename1);
			exit(1);
		}
	/* open target */
	if( ( target = open ( filename2, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR ) ) == -1 )
		{
			printf( "Open %s Error\n", filename2);
			exit(1);
		}

	gettimeofday(&start,NULL);	
	/* copy file */
	while( bytes_read = read( source, buffer, BUFFERCAP ) )
		{                                                                                                          bytes_sum+=bytes_read;         
			if( ( bytes_read==-1 ) && ( errno!=EINTR))  
				break; 
			else if(bytes_read>0)
				{
					ptr = buffer;
					while( bytes_write = write ( target, ptr, bytes_read))
						{
							if( ( bytes_write == -1 ) && ( errno != EINTR ) )
								break;            
							//							else if(bytes_write==bytes_read) break;/* 写完了所有读的字节 */
							else if(bytes_read==0) break;/* 写完了所有读的字节 */														else if(bytes_write>0) /* 只写了一部分,继续写 */
                          {
							  ptr += bytes_write;
							  bytes_read -= bytes_write;
                          }
						}
					if( bytes_write == -1 )/* 写的时候发生的致命错误 */
						break;
				}
		}

	close( source );
	close( target );

	gettimeofday(&end,NULL);
	//	time_use=(end.tv_sec-start.tv_sec);
	time_use=(end.tv_sec-start.tv_sec)*1000000+(end.tv_usec-start.tv_usec);//微秒
	printf("copy: %f time: %f s speed: %f B\n",bytes_sum,time_use/1000000,bytes_sum/time_use);
	
    return 0;

}


int main(int argc, char *argv[])
{
	char temp[20];
	int i;
	/* check args */
	if(argc!=3)
		{
			printf("fUNCTION:%s THE INFORMATION FROM SOURCEFILE TO TARGETFILE.\n\a",argv[0]);
			exit(1);
		}
			
	//			copyfile(argv[1],argv[2]) ;			
	for ( i = 0; i < atoi(argv[2]);; ++i)
		{
			
			sprintf(temp,"%d_%s",i,argv[1]);
			copyfile(argv[1],temp);
		}

	
	//			sprintf(temp,"%s_%d","name",1);
	//		printf("%s\n",temp);
	
	return 0;
			 
}
